from database.models import Users, Videos, Video_details
from outof_srv.settings import SECRET_KEY
from utils import get_banner_details
import json
import hashlib
import jwt
import datetime
from django.http import HttpRequest, JsonResponse, HttpResponse


def check_auth(token: str):
    try:
        return jwt.decode(token, SECRET_KEY, algorithms=['HS256'])['id']
    except jwt.ExpiredSignatureError as e:
        return e
    except:
        return 'Error token'


def login(request: HttpRequest):
    payload = json.loads(request.body)
    user_obj = Users.objects.filter(tele=payload.get('tele')).first()
    if not user_obj:
        return HttpResponse('Invalid User', status=400)
    passwd_md5 = hashlib.md5(payload['passwd'].encode()).hexdigest()
    if passwd_md5 == user_obj.user_passwd_hash:
        return JsonResponse({'name': user_obj.user_name, 'id': user_obj.user_id, 'token': jwt.encode(
            {'id': user_obj.user_id, 'exp': datetime.datetime.now() + datetime.timedelta(hours=3)}, key=SECRET_KEY)})
    return HttpResponse('Invalid', status=400)


def get_upload_videos(request: HttpRequest):
    id = check_auth(request.GET.get('token'))
    if type(id) != int:
        return HttpResponse(str(id), status=400)
    return JsonResponse({'payload': [get_banner_details(i) for i in Videos.objects.filter(author__user_id=id).all()]})


def get_operation_videos(request: HttpRequest):
    id = check_auth(request.GET.get('token'))
    op = request.GET.get('operation')
    if type(id) != int:
        return HttpResponse(str(id), status=400)
    return JsonResponse({'payload': [get_banner_details(i.video) for i in
                                     Video_details.objects.filter(user_id=id, operation_type=op).all()]})


def test_login(request: HttpRequest):
    return HttpResponse(check_auth(request.GET.get('token')))
